package com.vehicle.repair.service;

import com.vehicle.repair.model.PaymentRecord;
import com.vehicle.repair.model.Repairer;
import com.vehicle.repair.model.WorkOrder;
import com.vehicle.repair.repository.PaymentRecordRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class PaymentService {
    private final PaymentRecordRepository paymentRecordRepository;
    private final WorkOrderService workOrderService;
    private final RepairerService repairerService;

    public PaymentService(PaymentRecordRepository paymentRecordRepository,
                        WorkOrderService workOrderService,
                        RepairerService repairerService) {
        this.paymentRecordRepository = paymentRecordRepository;
        this.workOrderService = workOrderService;
        this.repairerService = repairerService;
    }

    public PaymentRecord createPaymentRecord(Integer orderId) {
        WorkOrder order = workOrderService.getWorkOrderById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Work order not found"));
        
        if (order.getStatus() != WorkOrder.OrderStatus.已完成) {
            throw new IllegalStateException("Payment can only be created for completed orders");
        }
        
        // Calculate total work hours and material cost
        double totalWorkHours = order.getWorkLogs().stream()
                .mapToDouble(WorkLog::getWorkHours)
                .sum();
        
        double materialCost = order.getMaterialUsages().stream()
                .mapToDouble(MaterialUsage::getTotalPrice)
                .sum();
        
        // Get the first repairer (assuming one repairer per order for simplicity)
        Repairer repairer = order.getRepairers().get(0);
        
        PaymentRecord record = new PaymentRecord();
        record.setOrder(order);
        record.setRepairer(repairer);
        record.setWorkHours(totalWorkHours);
        record.setHourlyRate(repairer.getHourlyRate());
        record.setMaterialCost(materialCost);
        record.setPayDate(LocalDate.now());
        
        return paymentRecordRepository.save(record);
    }

    public Optional<PaymentRecord> getPaymentRecordById(Integer id) {
        return paymentRecordRepository.findById(id);
    }

    public List<PaymentRecord> getPaymentRecordsByRepairer(Integer repairerId) {
        Repairer repairer = repairerService.getRepairerById(repairerId)
                .orElseThrow(() -> new IllegalArgumentException("Repairer not found"));
        return paymentRecordRepository.findByRepairer(repairer);
    }

    public Optional<PaymentRecord> getPaymentRecordByOrder(Integer orderId) {
        WorkOrder order = workOrderService.getWorkOrderById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Work order not found"));
        return paymentRecordRepository.findByOrder(order);
    }

    public double getTotalIncomeForRepairer(Integer repairerId) {
        return paymentRecordRepository.findByRepairer_RepairerId(repairerId)
                .stream()
                .mapToDouble(PaymentRecord::getTotalIncome)
                .sum();
    }
}
